package org.chs.ts.batch.exception;


import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.chs.ts.base.batch.exec.entity.BatchClearBasicTaskExec;
import org.chs.ts.base.batch.exec.entity.BatchClearBasicTaskStepExec;
import org.chs.ts.base.batch.log.entity.BatchClearBasicLog;
import org.chs.ts.base.common.util.SpringContextUtils;
import org.chs.ts.base.constant.CommonConstant;
import org.chs.ts.batch.constant.TaskStatusCodeEnum;
import org.chs.ts.batch.factory.SernoFactory;
import org.chs.ts.batch.threadservice.BatchServiceBase;
import org.chs.ts.batch.util.ConvertToUtil;

import org.chs.ts.batch.service.IBatchClearBasicLogService;
import org.chs.ts.batch.service.IBatchClearBasicTaskExecService;


import java.util.HashMap;

/**
 * @Compay 盛唐天行
 * @Author: wuwei
 * @Censor By wuwei
 * @Sence 2023/1/5 15:36
 * @Modify 2023/1/5 15:36
 * @Description
 */
@Slf4j
public class TaskExecException extends Exception {

    private static final String SERNO_TYPE = "task";

    @Getter
    private final String code;

    @Getter
    private final String taskExecId;

    private IBatchClearBasicTaskExecService clearBasicTaskExecService;

    protected IBatchClearBasicLogService clearBasicLogService;



    /**
     *
     * @param str 异常信息
     * @param taskStatusCodeEnum 异常码值
     * @param taskExecId 跑批子任务ID
     * @Description:  该方法不会回写跑批任务状态
     */
    public TaskExecException(String str, TaskStatusCodeEnum taskStatusCodeEnum, String taskExecId) {
        super(str);
        this.code = taskStatusCodeEnum.getRetCd();
        this.taskExecId = taskExecId;

        // 初始化 common spring 对象
        initSpring();

    }

    /**
     *
     * @param str 异常信息
     * @param taskStatusCodeEnum 异常码值
     * @param batchServiceBase 跑批子任务ID
     * @Description:  该方法会回写跑批任务状态
     */
    public TaskExecException(String str, TaskStatusCodeEnum taskStatusCodeEnum, BatchServiceBase<BatchClearBasicTaskExec, BatchClearBasicTaskStepExec> batchServiceBase) {
        super(str);
        this.code = taskStatusCodeEnum.getRetCd();
        this.taskExecId = batchServiceBase.getTaskObject().getTaskExecid();

        // 初始化 common spring 对象
        initSpring();
        // 插入 mwbp_clear_basic_log
        createClearBasicLog(batchServiceBase);
        log.info(this.getMessage());
    }



    protected void initSpring() {
        this.clearBasicLogService =  SpringContextUtils.getBean(IBatchClearBasicLogService.class);
        this.clearBasicTaskExecService =  SpringContextUtils.getBean(IBatchClearBasicTaskExecService.class);
        //this.environment = (Environment) SpringContextUtils.getBean("environment");

    }

    protected void createClearBasicLog(BatchServiceBase<BatchClearBasicTaskExec, BatchClearBasicTaskStepExec> batchServiceBase) {
        if (batchServiceBase == null || batchServiceBase.getTaskObject() == null) {
            return;
        }

        BatchClearBasicTaskExec taskExec = batchServiceBase.getTaskObject();
        String ip = batchServiceBase.getIp();
        String port = batchServiceBase.getPort();
        String path = batchServiceBase.getPath();
        long startTime = batchServiceBase.getTaskStartTime();
        String endTime = ConvertToUtil.getRunningTime();
        String execStatus = "4";
        taskExec.setExecStatus(execStatus);


        // clearBasicTaskExecService.updateById(taskExec);
        String errMsg = "";

        try {
            batchServiceBase.writeBackResultForRedis(taskExec);

            clearBasicTaskExecService.updateByObject(taskExec);
        } catch (Exception e) {

            errMsg = "batchClearBasicTaskExecService updateByObject:" + taskExec.getTaskExecid() + ";" + e.getMessage();

            log.error(errMsg);
            //throw new TaskExecException(errMsg, TaskStatusCodeEnum.TASK_RUNNING_RUNNINGERROR, taskExec.getTaskExecid());

        }

        String finalErrMsg = errMsg;
        clearBasicLogService.save(
                ConvertToUtil.convertToV(new BatchClearBasicLog(), batchServiceBase.getTaskObject(), new HashMap<String, Object>() {
                    {
                        put("taskPubId", SernoFactory.createSerno(SERNO_TYPE));
                        put("stepNo", "");
                        put("execStatus", execStatus);
                        put("shouldExecDate", batchServiceBase.getTaskObject().getExecDate());
                        put("targetCode", "");
                        put("startTime", ConvertToUtil.timeMillisFormatDateTime(startTime));
                        put("endTime", ConvertToUtil.timeMillisFormatDateTime(Long.valueOf(endTime)));
                        put("threadUuid", "");
                        put("serverName", path);
                        put("serverIp", ip + ":" + port);
                        put("rtnCode", CommonConstant.RTN_CODE_FAILED);
                        put("rtnDesc", getLogMessage(finalErrMsg +getMessage()));
                    }
                })
        );
    }

    protected String getLogMessage(String msg) {
        int strLength = 1800;
        //return msg.length() > strLength ? msg.substring(0, strLength) : msg;
        return msg.substring(0, Math.min(strLength, msg.length()));
    }


}
